package com.example.ccj.b.c.ui;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.IntDef;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.widget.ViewPager2;

import com.example.ccj.R;
import com.example.ccj.b.c.custom.adapter.AdapterViewPage2;
import com.example.ccj.u.LogUtils;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Target;
import java.util.List;

/**
 * 基于tablayout的导航栏
 */
public class NavigationPageOnTabLayout extends RelativeLayout {
    private static final String TAG = "底部导航栏";
    private final ViewPager2 viewPager2;
    private final TabLayout tabLayout;
    private final Button rightButton;

    //默认加载方式
    public static final int TAB_LOAD_TYPE_DEFAULT = 0;
    //默认自定义布局
    public static final int TAB_LOAD_TYPE_DEFAULT_CUSTOM = 1;
    //自定义布局
    public static final int TAB_LOAD_TYPE_CUSTOM = 2;
    //只显示文字
    public static final int TAB_LOAD_TYPE_ONLY_TEXT = 3;
    //加载方式注解
    @IntDef(value = {TAB_LOAD_TYPE_DEFAULT, TAB_LOAD_TYPE_DEFAULT_CUSTOM, TAB_LOAD_TYPE_CUSTOM,TAB_LOAD_TYPE_ONLY_TEXT}) //取值
    @Inherited
    @Target({ElementType.PARAMETER,ElementType.FIELD}) //作用域
    public @interface LoadType { }
    //导航栏加载方式
    private @LoadType int loadType = TAB_LOAD_TYPE_DEFAULT_CUSTOM;

    //是否显示图片
    private boolean isShowIcon = true;
    //更改选择时是否更改背景颜色
    private boolean isChangeBackGround = false;
    //文字大小
    private int textSize;
    //数据
    private List<TableAndViewPageBean> data;
    //是否将导航列表放在顶部
    private boolean isTop = false;
    //是否允许导航栏滚动
    private boolean isRoll = false;
    //导航栏高度
    private int tabHeight = 0;
    //上一个选中的tab下标
    private int oldId;
    //自定义布局接口
    private TabLayoutLoadCustomView tabLayoutLoadCustomView;

    public NavigationPageOnTabLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.slef_view_page_fragment, this);
        viewPager2 = findViewById(R.id.view_pager);
        tabLayout = findViewById(R.id.tab_layout);
        rightButton = findViewById(R.id.slef_view_page2_button);
    }

    /**
     * 创建
     */
    public void build(){

        //根据导航条位置设置布局格式
        //顶部布局
        if (isTop) {
            //设置viewPager2布局
            RelativeLayout.LayoutParams layoutParams = (LayoutParams) viewPager2.getLayoutParams();
            layoutParams.addRule(RelativeLayout.BELOW,R.id.tab_layout);
            viewPager2.setLayoutParams(layoutParams);
            //设置tablayout高度
            if (tabHeight != 0) {
                RelativeLayout.LayoutParams layoutParams1 = new LayoutParams(LayoutParams.MATCH_PARENT,tabHeight);
                tabLayout.setLayoutParams(layoutParams1);
            }
            //底部布局
        } else {
            //设置viewPager2布局
            RelativeLayout.LayoutParams layoutParams = (LayoutParams) viewPager2.getLayoutParams();
            layoutParams.addRule(RelativeLayout.ABOVE,R.id.tab_layout);
            viewPager2.setLayoutParams(layoutParams);

            //设置tablayout布局
            RelativeLayout.LayoutParams layoutParams1;
            if (tabHeight != 0) layoutParams1 = new LayoutParams(LayoutParams.MATCH_PARENT,tabHeight);
            else layoutParams1 = (LayoutParams) tabLayout.getLayoutParams();
            layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            tabLayout.setLayoutParams(layoutParams1);
        }

        //tabLayout是否可滚动
        if (isRoll) tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
//        LogUtils.d(TAG, "build() loadType: " + loadType);
        if (loadType != TAB_LOAD_TYPE_DEFAULT) {
            tabLayout.setBackgroundColor(Color.parseColor("#E3E3E3"));
            tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                //选择之后的
                @Override
                public void onTabSelected(TabLayout.Tab tab) {
//                    LogUtils.d(TAG, "onTabSelected() 设置选择后图片: " + "");
                    int selectId = tabLayout.getSelectedTabPosition();
                    oldId = selectId;
                    if (loadType == TAB_LOAD_TYPE_DEFAULT_CUSTOM) {
                        if (isShowIcon && data.get(selectId).getIconSelected() != 0 && tab.getCustomView() != null) {
                            ImageView imageView = tab.getCustomView().findViewById(R.id.imageview);
                            imageView.setImageResource(data.get(selectId).getIconSelected());
                        }
                    } else if (loadType == TAB_LOAD_TYPE_CUSTOM) {
                        View view = tabLayoutLoadCustomView.onTabSelected(tab, selectId);
                        if (view != null) tab.setCustomView(view);
                    } else if (loadType == TAB_LOAD_TYPE_ONLY_TEXT) {
                        TextView textView = tab.getCustomView().findViewById(R.id.textview111);
                        textView.setBackgroundResource(R.color.tab_selecd_bacakground);
                    }
                }

                //未选中的
                @Override
                public void onTabUnselected(TabLayout.Tab tab) {
                    //自定义布局
                    if (loadType == TAB_LOAD_TYPE_DEFAULT_CUSTOM ) {
                        if (isShowIcon && data.get(oldId).getIcon() != 0 && tab.getCustomView() != null) {
                            ImageView imageView = tab.getCustomView().findViewById(R.id.imageview);
                            imageView.setImageResource(data.get(oldId).getIcon());
                        }
                    } else if (loadType == TAB_LOAD_TYPE_CUSTOM) {
                        View view = tabLayoutLoadCustomView.onTabUnselected(tab, oldId);
                        if (view != null) tab.setCustomView(view);
                    } else if (loadType == TAB_LOAD_TYPE_ONLY_TEXT) {
                        TextView textView = tab.getCustomView().findViewById(R.id.textview111);
                        textView.setBackgroundResource(R.color.tab_no_selecd_bacakground);
                    }
                }
                @Override
                public void onTabReselected(TabLayout.Tab tab) {}
            });
        } else {
            tabLayout.setBackgroundColor(Color.WHITE);
            tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    int selectId = tabLayout.getSelectedTabPosition();
                    TableAndViewPageBean tableAndViewPageBean = data.get(selectId);
                    if (tableAndViewPageBean.getBottomIconSelectListener() != null) {
                        tableAndViewPageBean.getBottomIconSelectListener().onSelected(tableAndViewPageBean);
                    }
                }
                @Override
                public void onTabUnselected(TabLayout.Tab tab) {}
                @Override
                public void onTabReselected(TabLayout.Tab tab) {}
            });
        }

        if (data != null) {
            //设置ViewPage2的Adapter
            AdapterViewPage2 adapterViewPage = new AdapterViewPage2((FragmentActivity) getContext(),data);
            viewPager2.setAdapter(adapterViewPage);

            //tabLayout和viewPager2关联
            //smoothScroll 参数为true时点击tablayout标签会从当前页面滚动到点击的页面
            //这个参数决定了点击tab按钮fragment是懒加载还是重新加载
            new TabLayoutMediator(tabLayout, viewPager2,true,false, (tab, position) -> {
                //设置布局
                switch (loadType){
                    case TAB_LOAD_TYPE_DEFAULT:
                        if (data.get(position).getIcon() != 0) tab.setIcon(data.get(position).getIcon());
                        tab.setText(data.get(position).getText());
                        break;
                    case TAB_LOAD_TYPE_DEFAULT_CUSTOM:
                        tab.setCustomView(makeTabView(position));
                        break;
                    case TAB_LOAD_TYPE_CUSTOM:
                        View view = tabLayoutLoadCustomView.loadTabLayoutView(tab, position);
                        if (view != null) tab.setCustomView(view);
                        break;
                    case TAB_LOAD_TYPE_ONLY_TEXT:
                        tab.setCustomView(make1TabView(position));
                        break;
                }
            }).attach();
        }
    }

    //禁止滑动
    public NavigationPageOnTabLayout noSlide(){
        viewPager2.setUserInputEnabled(false);
        return this;
    }

    /**
     * 引入布局设置图标和标题
     * @param position 当前选择的选项卡
     * @return view
     */
    private View makeTabView(int position){
        View tabView = LayoutInflater.from(getContext()).inflate(R.layout.tab_text_icon,null);
        TextView textView = tabView.findViewById(R.id.textview);
        ImageView imageView = tabView.findViewById(R.id.imageview);
        textView.setText(data.get(position).getText());
        textView.setTextSize(textSize);
        RelativeLayout icon1 = tabView.findViewById(R.id.slef_view_page_fragment_tab_icon111);
        if (isShowIcon) {
            if (data.get(position).getIcon() != 0) imageView.setImageResource(data.get(position).getIcon());
        } else {
            icon1.setVisibility(GONE);
        }
        return tabView;
    }

    private View make1TabView(int position){
        View tabView = LayoutInflater.from(getContext()).inflate(R.layout.tab_text_defult,null);
        TextView textView = tabView.findViewById(R.id.textview111);
        textView.setText(data.get(position).getText());
        textView.setTextSize(textSize);
        return tabView;
    }



    //自定义布局接口
    public interface TabLayoutLoadCustomView {
        //加载方式
        View loadTabLayoutView(TabLayout.Tab tab, int position);
        //选中后的tab
        //可在该回调中通过tab.getCustomView().findViewById(控件id)获取控件直接修改，返回NULL即可
        View onTabSelected(TabLayout.Tab tab, int position);
        //未选中的tab
        //可在该回调中通过tab.getCustomView().findViewById(控件id)获取控件直接修改，返回NULL即可
        View onTabUnselected(TabLayout.Tab tab, int position);//修改前的tab
    }

    //设置加载方式为默认
    public NavigationPageOnTabLayout setLoadTypeToDefault(){
        loadType = TAB_LOAD_TYPE_DEFAULT;
        return this;
    }

    /**
     * 设置右侧按钮
     * @param name 按钮显示的文字
     * @param clickListener 按钮点击事件
     * @return
     */
    public NavigationPageOnTabLayout setRightButton(String name,View.OnClickListener clickListener){
        this.rightButton.setVisibility(View.VISIBLE);
        this.rightButton.setText(name);
        this.rightButton.setOnClickListener(clickListener);
        return this;
    }

    /**
     * 设置角标
     * @param position
     * @param number
     */
    public void setJiaoBiaoNO(@IntRange(from = 0) int position, int number){
        if (position > data.size()-1) {
            LogUtils.e(TAG,"角标数字设置失败，TAB下标过大， 最大"+(data.size()-1));
            return;
        }
        if (loadType == TAB_LOAD_TYPE_DEFAULT_CUSTOM) {
            TabLayout.Tab tabAt = tabLayout.getTabAt(position);
            if (tabAt != null && tabAt.getCustomView() != null) {
                RelativeLayout relativeLayout = tabAt.getCustomView().findViewById(R.id.jiao_biao);
                if (number < 1) {
                    relativeLayout.setVisibility(GONE);
                    return;
                }
                relativeLayout.setVisibility(VISIBLE);
                TextView textView = tabAt.getCustomView().findViewById(R.id.jiao_biao_text);
                textView.setText(String.valueOf(number));
                return;
            }
            //打印日志
            LogUtils.e(TAG,"角标数字设置失败，当前tab为空或默认布局为空");
        }
        //打印日志
        LogUtils.e(TAG,"角标数字设置失败，当前加载方式不是默认布局");
    }

    //设置预加载fragment数量不包含当前页面
    public NavigationPageOnTabLayout setOffscreenPageLimit(@ViewPager2.OffscreenPageLimit int limit){
        viewPager2.setOffscreenPageLimit(limit);
        return this;
    }

    /**
     * 设置数据
     */
    public NavigationPageOnTabLayout setData(@NonNull List<TableAndViewPageBean> data){
        this.data = data;
        return this;
    }

    /**
     * 导航条是否在顶部
     * 根据传入的参数设置布局
     */
    public NavigationPageOnTabLayout isTop(boolean isTop){
        this.isTop = isTop;
        return this;
    }

    /**
     * 导航条是否可以滚动
     * 根据传入的参数设置布局
     */
    public NavigationPageOnTabLayout isRoll(boolean isRoll){
        this.isRoll = isRoll;
        return this;
    }

    /**
     * 设置tabLayout的高度
     */
    public NavigationPageOnTabLayout setTabHeight(@IntRange(from = 20, to = 100) int height){
        this.tabHeight = height;
        return this;
    }

    /**
     * 设置自定义view
     */
    public NavigationPageOnTabLayout setTabCustomLayout(TabLayoutLoadCustomView tabLayoutLoadCustomView){
        this.tabLayoutLoadCustomView = tabLayoutLoadCustomView;
        if (tabLayoutLoadCustomView != null) {
            this.loadType = TAB_LOAD_TYPE_CUSTOM;
        }
        return this;
    }

    public NavigationPageOnTabLayout onlyText(){
        this.loadType = TAB_LOAD_TYPE_ONLY_TEXT;
        return this;
    }

    public boolean isShowIcon() {
        return isShowIcon;
    }

    public NavigationPageOnTabLayout setShowIcon(boolean showIcon) {
        isShowIcon = showIcon;
        return this;
    }

    public boolean isChangeBackGround() {
        return isChangeBackGround;
    }

    public NavigationPageOnTabLayout setChangeBackGround(boolean changeBackGround) {
        isChangeBackGround = changeBackGround;
        return this;
    }

    public int getTextSize() {
        return textSize;
    }

    public NavigationPageOnTabLayout setTextSize(int textSize) {
        this.textSize = textSize;
        return this;
    }
}
